<template>
    <div>
        <div v-bind:class="{ hide: isShowProtocolActive, page: true, 'register-view': true }">
            <wv-header title="注册用户" fixed>
                <div class="btn-back" slot="left">
                    <i class="iconfont iot-back" @click="$router.push({ name: 'login' })"></i>
                </div>
            </wv-header>
            <div class="main-header-fixed">
                <div class="login-wrapper">
                    <wv-group>
                        <wv-input label="手机号码" placeholder="手机号码" v-model="fields.mobile"></wv-input>
                        <wv-input class="password-input" label="密 码" type="password" placeholder="密码" v-model="fields.password"></wv-input>
                        <wv-input label="确认密码" type="password" placeholder="确认密码" v-model="fields.re_password"></wv-input>
                        <wv-cell title="所在城市" is-link :value="address | pickerValueFilter" @click.native="addressPickerShow = true"></wv-cell>
                        <wv-input type="number" label="" placeholder="验证码" v-model="fields.auth_code">
                            <button ref="authCodeBtn" :disabled="authCodeBtnDisabled" class="weui-vcode-btn" slot="ft" @click="getAuthCode">{{ authCodeText }}</button>
                        </wv-input>
                        <wv-input class="invite-code-input"  label="邀请码" placeholder="(选填)" v-model="fields.invite_code"></wv-input>
                    </wv-group>
                    <wv-button type="primary" @click="register">注册</wv-button>
                    <div class="protocol">
                        <input type="checkbox" v-model="protocolChecked"></input>
                        <span @click="toggleProtocolView">用户注册协议</span>
                    </div>
                </div>
                <wv-picker v-model="addressPickerShow" ref="addressPicker" :slots="addressSlots" @change="onAddressChange"  @confirm="confirmAddress"></wv-picker>
            </div>
        </div>
        <div v-bind:class="{ hide: !isShowProtocolActive, page: true, 'protocol-view': true }">
            <wv-header title="用户注册协议" fixed>
                <div class="btn-back" slot="left">
                    <i class="iconfont iot-back" @click="toggleProtocolView"></i>
                </div>
            </wv-header>
            <div class="main-header-fixed container-protocol">
                <div class="tip">尊敬的用户，欢迎您使用加电侠。在访问和使用加电侠的同时，也请您仔细阅读我们的协议条款。您需要完全接受本协议才能注册成为我们的用户。一经注册，即视为同意本协议中的所有条款内容，需要遵守协议中的所有条款。</div>
                <div class="hide">⓪①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳㉑㉒㉓㉔㉕㉖㉗㉘㉙㉚㉛㉜㉝㉞㉟</div>
                <div>
                    <ul class="list">
                        <li>
                            <div>一、总则</div>
                            <div class="sub-list">
                                <ul>
                                    <li>加电侠的所有权和运营权归雷侠科技有限公司所有</li>
                                    <li> 用户在注册之前，应当仔细阅读本协议，并同意遵守本协议后方可成为注册用户。一旦注册成功，则用户与加电侠之间自动形成协议关系，用户应当受本协议的约束。用户在使用特殊的服务或产品时，应当同意接受相关协议后方能使用。</li>
                                    <li>本协议则可由加电侠随时更新，用户应当及时关注并同意本站不承担通知义务。本站的通知、公告、声明或其它类似内容是本协议的一部分</li>
                                </ul>
                            </div>
                        </li>
                        <li>
                            <div>二、服务内容</div>
                            <div class="sub-list">
                                <ul>
                                    <li>加电侠的具体内容由本站根据实际情况提供。</li>
                                </ul>
                            </div>
                        </li>
                        <li>
                            <div>三、用户帐号</div>
                            <div class="sub-list">
                                <ul>
                                    <li>经本站注册系统完成注册程序并通过身份认证的用户即成为正式用户，可以获得本站规定用户所应享有的一切权限；未经认证仅享有本站规定的部分会员权限。加电侠有权对会员的权限设计进行变更。</li>
                                    <li>用户只能按照注册要求使用真实手机号码注册。用户有义务保证密码和帐号的安全，用户利用该密码和帐号所进行的一切活动引起的任何损失或损害，由用户自行承担全部责任，本站不承担任何责任。</li>
                                    <li>如用户发现帐号遭到未授权的使用或发生其他任何安全问题，应立即修改帐号密码并妥善保管，如有必要，请通知本站。</li>
                                    <li>因黑客行为或用户的保管疏忽导致帐号非法使用，本站不承担任何责任。</li>
                                </ul>
                            </div>
                        </li>
                        <li>
                            <div>四、附则</div>
                            <div class="sub-list">
                                <ul>
                                    <li>本协议的订立、执行和解释及争议的解决均应适用中华人民共和国法律。</li>
                                    <li>如本协议中的任何条款无论因何种原因完全或部分无效或不具有执行力，本协议的其余条款仍应有效并且有约束力。</li>
                                    <li>本协议解释权及修订权归雷侠科技有限公司所有。</li>
                                </ul>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</template>

<style>
    .hide {
        display: none;
    }
    .protocol {
        text-align: center;
        margin-top: 50px;
        font-size: 12px;
        color: #888888;
        text-decoration: underline;
    }
    .weui-cell.password-input .weui-label {
        letter-spacing: 14px;
    }
    .weui-cell.invite-code-input .weui-label {
        letter-spacing: 9px;
    }
</style>

<script>
    import util from '@/libs/util';
    import regionsData from '@/config/regions.json';

    function getProvince () {
        let obj = [];

        for (let i in regionsData) {
            obj.push(regionsData[i].name);
        }

        return obj;
    }

    let provinces = getProvince(regionsData);

    // 获取某一省下的市
    function getCities (province) {
        let format_arr = [];

        let citys = [];
        for (let i in regionsData) {
            if (regionsData[i].name == province) {
                citys = regionsData[i].children;
                break;
            }
        }

        for (let i in citys) {
            format_arr.push(citys[i].name);
        }

        return format_arr;
    }

    // 获取某一市下的区/县
    function getAreas (province, city) {
        let format_arr = [];

        let citys = [];
        for (let i in regionsData) {
            if (regionsData[i].name == province) {
                citys = regionsData[i].children;
                break;
            }
        }

        let districts = [];
        for (let i in citys) {
            if (citys[i].name == city) {
                districts = citys[i].children;
                break;
            }
        }

        for (let i in districts) {
            format_arr.push(districts[i].name);
        }

        return format_arr;
    }

    export default {
        data () {
            return {
                regions: [],
                regionsData: regionsData,
                addressPickerShow: false,
                address: '',
                addressSlots: [
                    {
                        values: provinces
                    },
                    {
                        values: []
                    },
                    {
                        values: []
                    }
                ],

                authCodeBtnDisabled: false,
                authCodeText: '获取验证码',

                firstLoaded: false,
                isShowProtocolActive: false,

                protocolChecked: false,

                fields: {
                    mobile: '',
                    auth_code: '',
                    invite_code: '',
                    password: '',
                    re_password: '',
                    province_code: '',
                    city_code: '',
                    district_code: '',
                    wx_official_open_id: '',
                    wx_union_id: ''
                }
            }
        },

        mounted () {
            this.getRegions();

            if (window.wechat_user && window.wechat_user.hasOwnProperty('id')) {
                this.fields.wx_official_open_id = window.wechat_user.id;

                if (window.wechat_user.hasOwnProperty('union_id')) {
                    this.fields.wx_union_id = window.wechat_user.union_id;
                }
            }
        },

        methods: {
            toggleProtocolView () {
                this.isShowProtocolActive = !this.isShowProtocolActive;
                this.firstLoaded = true;
            },

            register () {
                if (this.validatorForm(this.fields)) {
                    util.ajax.post('/api/user/register', this.fields).then((resp) => {
                        if (resp.data.status == true) {
                            this.$root.success(resp.data.message);
                            this.$router.push({
                                name: 'login'
                            });
                        } else {
                            this.$root.error(resp.data.message);
                        }
                    }).catch((e) => {
                        util.handleApiException(e, this, '注册用户失败');
                    })
                }
            },

            getAuthCode () {
                if (/^1\d{10}$/.test(this.fields.mobile)) {
                    this.authCodeBtnDisabled = true;
                    util.ajax.post('/api/user/register/authcode', {mobile: this.fields.mobile}).then((resp) => {
                        if (resp.data.status == true) {
                            this.$root.success(resp.data.message);
                            this.authCodeTimer();
                        } else {
                            this.$root.error(resp.data.message);
                            this.authCodeBtnDisabled = false;
                        }
                    }).catch((e) => {
                        util.handleApiException(e, this, '获取验证码失败');
                        this.authCodeBtnDisabled = false;
                    })
                } else {
                    this.$root.error('请输入正确的手机号码');
                }
            },

            authCodeTimer() {
                let that = this;
                that.authCodeBtnDisabled = true;
                let time = 60;
                window._authCodeTimer = setInterval(function () {
                    if (time == 1) {
                        clearInterval(window._authCodeTimer);
                        that.authCodeBtnDisabled = false;
                        that.authCodeText = '获取验证码';
                    } else {
                        time--;
                        that.authCodeText = time + '后重新获取';
                    }
                }, 1000);
            },

            validatorForm (data) {
                console.log(this.protocolChecked);

//                if (!/^[a-zA-Z0-9_-]{4,16}$/.test(data.name)) {
//                    this.$root.topTips('用户名格式4~16位字符（字母，数字，下划线，减号）');
//                    return false;
//                } else
                if (!this.protocolChecked) {
                    this.$root.topTips('请选择同意用户注册协议');
                    return false;
                } else if (!/^1\d{10}$/.test(this.fields.mobile)) {
                    this.$root.topTips('请输入正确的手机号码');
                    return false;
                }  else if (data.password.length < 6 || data.password.length > 16) {
                    this.$root.topTips('密码必须在6~16个字符之间');
                    return false;
                } else if (data.password != data.re_password) {
                    this.$root.topTips('两次密码输入不一致，请重新输入');
                    return false;
                } else if (data.province_code.length < 3 || data.city_code.length < 3 || data.district_code.length < 3) {
                    this.$root.topTips('选择城市');
                    return false;
                } else if (data.auth_code.length == '') {
                    this.$root.topTips('请输入验证码');
                    return false;
                }

                return true;
            },

            onAddressChange (picker, value) {
                console.log(value)
                picker.setSlotValues(1, getCities(value[0]))
                picker.setSlotValues(2, getAreas(value[0], value[1]))
            },

            confirmAddress (picker) {
                this.address = picker.getValues();
                this.getRegionCode(picker.getValues());
                console.log(this.fields);
            },

            getRegionCode (values) {
                let province = this.regions.find((n) => n.value == values[0]);
                let city = province.children.find((n) => n.value == values[1]);
                let district = city.children.find((n) => n.value == values[2]);

                this.fields.province_code = province.key;
                this.fields.city_code = city.key;
                this.fields.district_code = district.key;
            },

            getRegions () {
                const formatTree = (arr) => {
                    let regions = [];
                    for (let i in arr) {
                        if (arr[i].disabled) {
                            continue;
                        }

                        let node = {};
                        node.key = arr[i].code;
                        node.value = arr[i].name;

                        if (arr[i].hasOwnProperty('children')) {
                            node.children = formatTree(arr[i].children);
                        }

                        regions.push(node);
                    }
                    return regions;
                };

                this.regions = formatTree(this.regionsData);
            },
        },

        filters: {
            pickerValueFilter (val) {
                if (Array.isArray(val)) {
                    return val.join('/')
                } else {
                    return '请选择'
                }
            },
        }
    }
</script>